﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

using System.IO;

using System.Xml.Linq;

namespace Lottery.MediaData.Core {
    public static class DataHelper {

        /// <summary>
        /// 存放数据的目录。
        /// </summary>
        public static string DataPath {
            get {
                return System.Windows.Forms.Application.StartupPath + @"\Data\";
            }
        }

        /// <summary>
        /// 删除后的数据存放的目录
        /// </summary>
        public static string RecyleBinPath {
            get {
                return System.Windows.Forms.Application.StartupPath + @"\RecyleBin\";
            }
        }

        public static string GetExcelPath(int maxCount) {
            return System.Windows.Forms.Application.StartupPath
                + @"\" + maxCount.ToString() + @"-Excel\";
        }

        public static string ExcelPath_14 {
            get {
                return System.Windows.Forms.Application.StartupPath + @"\14-Excel\";
            }
        }

        public static string ExcelPath_09 {
            get {
                return System.Windows.Forms.Application.StartupPath + @"\9-Excel\";
            }
        }

        public static void CheckDirectory() {
            var dirs = new string[] {DataPath, ExcelPath_09, ExcelPath_14, FTHelper.TouZhuPath_09,
                FTHelper.TouZhuPath_14};
            foreach (var dir in dirs) {
                if (!Directory.Exists(dir))
                    Directory.CreateDirectory(dir);
            }

            //删除原来的目录
            var old = new List<string>();
            old.Add(System.Windows.Forms.Application.StartupPath + @"\Excel\");
            old.Add(System.Windows.Forms.Application.StartupPath + @"\用户投注表\");
            foreach (var dir in old) {
                try {
                    if (Directory.Exists(dir)) new DirectoryInfo(dir).Delete(true);
                } catch {
                    // do nothing
                }
            }
        }

        /// <summary>
        /// 检查给定的期数是否存在
        /// </summary>
        /// <param name="qiShu">期数</param>
        /// <returns>true：存在</returns>
        public static bool IndexExists(string qiShu) {
            var data = from item in Directory.GetFiles(DataPath)
                       where Path.GetFileNameWithoutExtension(item) == qiShu
                       select item;
            return data.Count() == 1;
        }


        /// <summary>
        /// 新增期数
        /// </summary>
        /// <param name="qiShu">期数</param>
        public static void AddIndex(string qiShu) {
            var xml = new XElement("root",
                            new XElement("MaxCount",
                                new XAttribute("value", 14),
                                new XAttribute("cc", ""),
                                new XElement("T1"),
                                new XElement("T2"),
                                new XElement("T3"),
                                new XElement("T4"))
                            );
            xml.Save(DataPath + qiShu + ".xml");
        }

        /// <summary>
        /// 删除期数
        /// </summary>
        /// <param name="qiShu">期数</param>
        public static void DeleteIndex(string qiShu) {
            var fileName = DataPath + qiShu + ".xml";
            if (File.Exists(fileName)) {
                if (!Directory.Exists(RecyleBinPath)) Directory.CreateDirectory(RecyleBinPath);

                var newFileName = RecyleBinPath + qiShu + "_" + Guid.NewGuid().ToString() + ".xml";
                File.Move(fileName, newFileName);
            }
        }

        /// <summary>
        /// 自动新增序号
        /// </summary>
        /// <param name="tableName">表名：T1 T2 T3 T4</param>
        /// <param name="qiShu"></param>
        public static string AutoIncSubIndex(string tableName, string qiShu,
            string cc, int maxCount) {
            var fileName = DataPath + qiShu + ".xml";

            var xml = XElement.Load(fileName);
            var maxCountValue = cc == string.Empty ? 14 : maxCount;
            var table = (from item in xml.Elements("MaxCount")
                         where (int)item.Attribute("value") == maxCountValue
                             && item.Attribute("cc").Value == cc
                         select item.Element(tableName)).SingleOrDefault();

            var data = from item in table.Elements("Input")
                       select (int)item.Attribute("order");
            int index;
            if (data.Count() != 0) {
                index = data.Max() + 1;
            } else {
                index = 1;
            }

            table.Add(new XElement("Input", new XAttribute("order", index)));

            xml.Save(fileName);

            return index.ToString();
        }

        /// <summary>
        /// 新增指定的序号(如果该序号已经存在，不会再重复创建)
        /// </summary>
        /// <param name="tableName">表名：T1 T2 T3 T4</param>
        /// <param name="qiShu"></param>
        public static string CreateSubIndex(string tableName, string qiShu,
            string cc, int maxCount, int subIndex) {
            var allSubIndex = GetSubIndexes(tableName, qiShu, cc, maxCount);

            var itemSubIndex = from item in allSubIndex
                               where item == subIndex.ToString()
                               select item;
            if (itemSubIndex.Count() != 0) {
                // 该序号已经存在，不用再创建
                return subIndex.ToString();
            }

            var fileName = DataPath + qiShu + ".xml";

            var xml = XElement.Load(fileName);
            var maxCountValue = cc == string.Empty ? 14 : maxCount;
            var table = (from item in xml.Elements("MaxCount")
                         where (int)item.Attribute("value") == maxCountValue
                             && item.Attribute("cc").Value == cc
                         select item.Element(tableName)).SingleOrDefault();

            int index = subIndex;

            table.Add(new XElement("Input", new XAttribute("order", index)));

            xml.Save(fileName);

            return index.ToString();
        }

        /// <summary>
        /// 删除序号
        /// </summary>
        /// <param name="tableName">表名：T1 T2 T3 T4</param>
        /// <param name="qiShu">期数</param>
        /// <param name="cc">场次组合</param>
        /// <param name="subIndex">序号</param>
        public static void DeleteSubIndex(string tableName, string qiShu, string cc, string subIndex, int maxCount) {
            var fileName = DataPath + qiShu + ".xml";
            var xml = XElement.Load(fileName);
            var maxCountValue = string.IsNullOrEmpty(cc) ? 14 : maxCount;
            var table = from item in xml.Elements("MaxCount")
                        where (int)item.Attribute("value") == maxCountValue
                        && item.Attribute("cc").Value == cc
                        select item.Element(tableName);
            var data = from item in table.Elements("Input")
                       where (int)item.Attribute("order") == int.Parse(subIndex)
                       select item;
            if (data != null) {
                data.Remove();
                xml.Save(fileName);
            }
        }

        /// <summary>
        /// 获得所有的足彩期数
        /// </summary>
        /// <returns></returns>
        public static string[] GetAllIndexes() {
            var result = from item in Directory.GetFiles(DataPath)
                         where Path.GetExtension(item) == ".xml"
                         orderby item descending
                         select Path.GetFileNameWithoutExtension(item);

            return result.ToArray();
        }

        /// <summary>
        /// 获得表一某期的子序号
        /// </summary>
        /// <param name="qiShu">期数</param>
        /// <returns></returns>
        public static string[] GetSubIndexes(string tableName, string qiShu,
            string cc, int maxCount) {
            string fileName = DataPath + qiShu + ".xml";

            var xml = XElement.Load(fileName);
            var maxCountValue = cc == string.Empty ? 14 : maxCount;
            var table = from item in xml.Elements("MaxCount")
                        where (int)item.Attribute("value") == maxCountValue
                        && item.Attribute("cc").Value == cc
                        select item.Element(tableName);

            var data = from item in table.Elements("Input")
                       orderby (int)item.Attribute("order") ascending
                       select item.Attribute("order").Value;

            return data.ToArray();
        }

        public static string[] GetT1SubIndexes(string qiShu, string cc, int maxCount) {
            return GetSubIndexes("T1", qiShu, cc, maxCount);
        }
        public static string[] GetT2SubIndexes(string qiShu, string cc, int maxCount) {
            return GetSubIndexes("T2", qiShu, cc, maxCount);
        }
        public static string[] GetT3SubIndexes(string qiShu, string cc, int maxCount) {
            return GetSubIndexes("T3", qiShu, cc, maxCount);
        }
        public static string[] GetT4SubIndexes(string qiShu, string cc, int maxCount) {
            return GetSubIndexes("T4", qiShu, cc, maxCount);
        }

        /// <summary>
        /// 获得表一某期某次的所有数据
        /// </summary>
        /// <param name="qiShu">期数</param>
        /// <param name="order">子序号</param>
        /// <param name="cc">场次组合</param>
        /// <param name="d">媒体数据</param>
        /// <param name="f">过滤数据</param>
        /// <param name="c">合并行</param>
        public static void LoadT1Data(string qiShu, string cc, int maxCount, string order,
            out List<DS> d, out List<FD> f, out CL c) {
            var fileName = DataPath + qiShu + ".xml";
            var xml = XElement.Load(fileName);

            var maxCountValue = cc == string.Empty ? 14 : maxCount;
            var table = from item in xml.Elements("MaxCount")
                        where (int)item.Attribute("value") == maxCountValue
                        && item.Attribute("cc").Value == cc
                        select item.Element("T1");

            var data = (from item in table.Elements("Input")
                        where item.Attribute("order").Value == order
                        select item.Elements("Data")).SingleOrDefault();

            var result = from item in data
                         select new DS((int)item.Attribute("three"), (int)item.Attribute("one"),
                              (int)item.Attribute("zero"), item.Attribute("prenumber").Value);

            d = result.ToList();

            var filter = (from item in table.Elements("Input")
                          where item.Attribute("order").Value == order
                          select item.Elements("Filter")).SingleOrDefault();

            var fr = from item in filter
                     select new FD((int)item.Attribute("mediaCount"), (int)item.Attribute("count"),
                         (int)item.Attribute("low"), (int)item.Attribute("up"),
                         item.Attribute("isAttended") == null ? true : (bool)item.Attribute("isAttended"));
            f = fr.ToList();

            var CLs = (from item in table.Elements("Input")
                       where item.Attribute("order").Value == order
                       select item.Elements("CL")).SingleOrDefault();
            var clsList = (from item in CLs
                           select new CL() {
                               From1 = item.Attribute("from1") == null ? -1 : (int)item.Attribute("from1"),
                               To1 = item.Attribute("to1") == null ? -1 : (int)item.Attribute("to1"),
                               From2 = item.Attribute("from2") == null ? -1 : (int)item.Attribute("from2"),
                               To2 = item.Attribute("to2") == null ? -1 : (int)item.Attribute("to2")
                           }).ToList();

            c = clsList.Count > 0 ? clsList[0] : new CL();
        }

        /// <summary>
        /// 保存表一的数据
        /// </summary>
        /// <param name="qiShu">期数</param>
        /// <param name="cc">场次组合</param>
        /// <param name="order">子序号</param>
        /// <param name="d">媒体数据</param>
        /// <param name="f">过滤数据</param>
        /// <param name="c">合并行</param>
        public static void SaveT1Data(string qiShu, string cc, int maxCount, string order, List<DS> d,
            List<FD> f, CL c) {
            string fileName = DataPath + qiShu + ".xml";

            var xml = XElement.Load(fileName);

            var maxCountValue = cc == string.Empty ? 14 : maxCount;
            var table = from item in xml.Elements("MaxCount")
                        where (int)item.Attribute("value") == maxCountValue
                        && item.Attribute("cc").Value == cc
                        select item.Element("T1");

            var data = (from item in table.Elements("Input")
                        where item.Attribute("order").Value == order
                        select item).SingleOrDefault();
            data.Elements("Data").Remove();
            data.Elements("Filter").Remove();
            data.Elements("CL").Remove();
            int index = 0;
            foreach (var item in d) {
                data.Add(new XElement("Data", new XAttribute("order", index++),
                    new XAttribute("three", item.Three), new XAttribute("one", item.One),
                    new XAttribute("zero", item.Zero), new XAttribute("prenumber", item.PreNumber)));
            }

            index = 0;
            foreach (var item in f) {
                data.Add(new XElement("Filter", new XAttribute("order", index++),
                    new XAttribute("mediaCount", item.MediaCount), new XAttribute("count", item.Count),
                    new XAttribute("low", item.Low), new XAttribute("up", item.Up),
                    new XAttribute("isAttended", item.IsAttended)));
            }

            data.Add(new XElement("CL", new XAttribute("from1", c.From1),
                new XAttribute("to1", c.To1), new XAttribute("from2", c.From2),
                new XAttribute("to2", c.To2)));

            xml.Save(fileName);
        }

        public static void LoadT2Data(string qiShu, string cc, int maxCount, string order,
            out List<SC> d, out List<FD> f, out CL c) {
            var fileName = DataPath + qiShu + ".xml";
            var xml = XElement.Load(fileName);

            var maxCountValue = cc == string.Empty ? 14 : maxCount;
            var table = from item in xml.Elements("MaxCount")
                        where (int)item.Attribute("value") == maxCountValue
                        && item.Attribute("cc").Value == cc
                        select item.Element("T2");

            var data = (from item in table.Elements("Input")
                        where item.Attribute("order").Value == order
                        select item.Elements("Data")).SingleOrDefault();

            var result = from item in data
                         select new SC() {
                             Three = (int)item.Attribute("three"), One = (int)item.Attribute("one"),
                             Zero = (int)item.Attribute("zero"), PreNumber = item.Attribute("prenumber").Value,
                             D = item.Attribute("d").Value, Z = item.Attribute("z").Value,
                             X = item.Attribute("x").Value
                         };

            d = result.ToList();

            var filter = (from item in table.Elements("Input")
                          where item.Attribute("order").Value == order
                          select item.Elements("Filter")).SingleOrDefault();

            var fr = from item in filter
                     select new FD((int)item.Attribute("mediaCount"), (int)item.Attribute("count"),
                         (int)item.Attribute("low"), (int)item.Attribute("up"),
                         item.Attribute("isAttended") == null ? true : (bool)item.Attribute("isAttended"));
            f = fr.ToList();

            var CLs = (from item in table.Elements("Input")
                       where item.Attribute("order").Value == order
                       select item.Elements("CL")).SingleOrDefault();
            var clsList = (from item in CLs
                           select new CL() {
                               From1 = item.Attribute("from1") == null ? -1 : (int)item.Attribute("from1"),
                               To1 = item.Attribute("to1") == null ? -1 : (int)item.Attribute("to1"),
                               From2 = item.Attribute("from2") == null ? -1 : (int)item.Attribute("from2"),
                               To2 = item.Attribute("to2") == null ? -1 : (int)item.Attribute("to2")
                           }).ToList();

            c = clsList.Count > 0 ? clsList[0] : new CL();
        }

        public static void SaveT2Data(string qiShu, string cc, int maxCount, string order, List<SC> d,
            List<FD> f, CL c) {
            string fileName = DataPath + qiShu + ".xml";

            var xml = XElement.Load(fileName);

            var maxCountValue = cc == string.Empty ? 14 : maxCount;
            var table = from item in xml.Elements("MaxCount")
                        where (int)item.Attribute("value") == maxCountValue
                        && item.Attribute("cc").Value == cc
                        select item.Element("T2");

            var data = (from item in table.Elements("Input")
                        where item.Attribute("order").Value == order
                        select item).SingleOrDefault();
            data.Elements("Data").Remove();
            data.Elements("Filter").Remove();
            data.Elements("CL").Remove();
            int index = 0;
            foreach (var item in d) {
                data.Add(new XElement("Data", new XAttribute("order", index++),
                    new XAttribute("three", item.Three), new XAttribute("one", item.One),
                    new XAttribute("zero", item.Zero), new XAttribute("prenumber", item.PreNumber),
                    new XAttribute("d", item.D), new XAttribute("z", item.Z),
                    new XAttribute("x", item.X)));
            }

            index = 0;
            foreach (var item in f) {
                data.Add(new XElement("Filter", new XAttribute("order", index++),
                    new XAttribute("mediaCount", item.MediaCount), new XAttribute("count", item.Count),
                    new XAttribute("low", item.Low), new XAttribute("up", item.Up),
                    new XAttribute("isAttended", item.IsAttended)));
            }

            data.Add(new XElement("CL", new XAttribute("from1", c.From1),
                new XAttribute("to1", c.To1), new XAttribute("from2", c.From2),
                new XAttribute("to2", c.To2)));

            xml.Save(fileName);
        }

        public static void LoadT3Data(string qiShu, string cc, int maxCount, string order,
            out List<DZX> d, out CellData f) {
            f = new CellData();
            var fileName = DataPath + qiShu + ".xml";
            var xml = XElement.Load(fileName);

            var maxCountValue = cc == string.Empty ? 14 : maxCount;
            var table = from item in xml.Elements("MaxCount")
                        where (int)item.Attribute("value") == maxCountValue
                        && item.Attribute("cc").Value == cc
                        select item.Element("T3");

            var data = (from item in table.Elements("Input")
                        where item.Attribute("order").Value == order
                        select item.Elements("Data")).SingleOrDefault();

            var result = from item in data
                         select new DZX() {
                             Three = (int)item.Attribute("three"), One = (int)item.Attribute("one"),
                             Zero = (int)item.Attribute("zero"), PreText = item.Attribute("pretext").Value,
                             D = item.Attribute("d").Value, Z = item.Attribute("z").Value,
                             X = item.Attribute("x").Value
                         };

            d = result.ToList();

            var filter = (from item in table.Elements("Input")
                          where item.Attribute("order").Value == order
                          select item).SingleOrDefault();

            var f1 = from item in filter.Elements("Filter")
                     orderby (int)item.Attribute("rowOrder") ascending
                     select new {
                         RowOrder = (int)item.Attribute("rowOrder"),
                         Count = (int)item.Attribute("count"),
                         Low = item.Attribute("low").Value,
                         Up = item.Attribute("up").Value,
                         Cols = from it in item.Elements("Col")
                                select new {
                                    ColOrder = (int)it.Attribute("colOrder"),
                                    Value = it.Attribute("value").Value
                                }
                     };

            int rowOrder = 0;
            foreach (var item in f1) {
                foreach (var it in item.Cols) {
                    f[it.ColOrder, item.RowOrder] = it.Value;
                }

                f.SetRowLow(rowOrder, item.Low);
                f.SetRowUp(rowOrder, item.Up);
                rowOrder++;
            }
        }

        public static void SaveT3Data(string qiShu, string cc, int maxCount,
            string order, List<DZX> d, CellData cellData) {
            string fileName = DataPath + qiShu + ".xml";

            var xml = XElement.Load(fileName);

            var maxCountValue = cc == string.Empty ? 14 : maxCount;
            var table = from item in xml.Elements("MaxCount")
                        where (int)item.Attribute("value") == maxCountValue
                        && item.Attribute("cc").Value == cc
                        select item.Element("T3");

            var data = (from item in table.Elements("Input")
                        where item.Attribute("order").Value == order
                        select item).SingleOrDefault();
            data.Elements("Data").Remove();
            data.Elements("Filter").Remove();
            int index = 0;
            foreach (var item in d) {
                data.Add(new XElement("Data", new XAttribute("order", index++),
                    new XAttribute("three", item.Three), new XAttribute("one", item.One),
                    new XAttribute("zero", item.Zero), new XAttribute("pretext", item.PreText),
                    new XAttribute("d", item.D), new XAttribute("z", item.Z),
                    new XAttribute("x", item.X)));
            }

            index = 0;
            for (int row = 0; row < cellData.RowCount; row++) {
                var e = new XElement("Filter", new XAttribute("rowOrder", row),
                                new XAttribute("count", cellData.GetSum(row)),
                                new XAttribute("low", cellData.GetRowLow(row)),
                                new XAttribute("up", cellData.GetRowUp(row)));
                data.Add(e);
                for (int col = 0; col < cellData.ColCount; col++) {
                    e.Add(new XElement("Col", new XAttribute("colOrder", col),
                                new XAttribute("value", cellData[col, row])));
                }
            }

            xml.Save(fileName);
        }

        public static void LoadT4Data(string qiShu, string cc, int maxCount, string order,
            out List<WZ> d, out CellData f, out string text) {
            f = new CellData();
            var fileName = DataPath + qiShu + ".xml";
            var xml = XElement.Load(fileName);

            var maxCountValue = cc == string.Empty ? 14 : maxCount;
            var table = from item in xml.Elements("MaxCount")
                        where (int)item.Attribute("value") == maxCountValue
                        && item.Attribute("cc").Value == cc
                        select item.Element("T4");

            var data = (from item in table.Elements("Input")
                        where item.Attribute("order").Value == order
                        select item.Elements("Data")).SingleOrDefault();

            var textData = (from item in table.Elements("Input")
                            where item.Attribute("order").Value == order
                            select item.Elements("Text")).SingleOrDefault();

            text = (from item in textData
                    select item.Attribute("value").Value).SingleOrDefault();

            if (string.IsNullOrEmpty(text)) {
                text = "大中小";
            }

            var result = from item in data
                         select new WZ() {
                             Three = item.Attribute("three").Value, One = item.Attribute("one").Value,
                             Zero = item.Attribute("zero").Value, PreText = item.Attribute("pretext").Value
                         };

            d = result.ToList();

            var filter = (from item in table.Elements("Input")
                          where item.Attribute("order").Value == order
                          select item).SingleOrDefault();

            var f1 = from item in filter.Elements("Filter")
                     orderby (int)item.Attribute("rowOrder") ascending
                     select new {
                         RowOrder = (int)item.Attribute("rowOrder"),
                         Count = (int)item.Attribute("count"),
                         Low = item.Attribute("low").Value,
                         Up = item.Attribute("up").Value,
                         Cols = from it in item.Elements("Col")
                                select new {
                                    ColOrder = (int)it.Attribute("colOrder"),
                                    Value = it.Attribute("value").Value
                                }
                     };

            int rowOrder = 0;
            foreach (var item in f1) {
                foreach (var it in item.Cols) {
                    f[it.ColOrder, item.RowOrder] = it.Value;
                }

                f.SetRowLow(rowOrder, item.Low);
                f.SetRowUp(rowOrder, item.Up);
                rowOrder++;
            }
        }

        public static void SaveT4Data(string qiShu, string cc, int maxCount,
            string order, List<WZ> d, CellData cellData, string text) {
            string fileName = DataPath + qiShu + ".xml";

            var xml = XElement.Load(fileName);

            var maxCountValue = cc == string.Empty ? 14 : maxCount;
            var table = from item in xml.Elements("MaxCount")
                        where (int)item.Attribute("value") == maxCountValue
                        && item.Attribute("cc").Value == cc
                        select item.Element("T4");

            var data = (from item in table.Elements("Input")
                        where item.Attribute("order").Value == order
                        select item).SingleOrDefault();
            data.Elements("Data").Remove();
            data.Elements("Filter").Remove();
            data.Elements("Text").Remove();
            data.Add(new XElement("Text", new XAttribute("value", text)));
            int index = 0;
            foreach (var item in d) {
                data.Add(new XElement("Data", new XAttribute("order", index++),
                    new XAttribute("three", item.Three), new XAttribute("one", item.One),
                    new XAttribute("zero", item.Zero), new XAttribute("pretext", item.PreText)));
            }

            index = 0;
            for (int row = 0; row < cellData.RowCount; row++) {
                var e = new XElement("Filter", new XAttribute("rowOrder", row),
                                new XAttribute("count", cellData.GetSum(row)),
                                new XAttribute("low", cellData.GetRowLow(row)),
                                new XAttribute("up", cellData.GetRowUp(row)));
                data.Add(e);
                for (int col = 0; col < cellData.ColCount; col++) {
                    e.Add(new XElement("Col", new XAttribute("colOrder", col),
                                new XAttribute("value", cellData[col, row])));
                }
            }

            xml.Save(fileName);
        }

        /// <summary>
        /// 保存奖号
        /// </summary>
        /// <param name="qiShu">期数</param>
        /// <param name="numbers">奖号</param>
        public static void SaveNumbers(string qiShu, string[] numbers) {
            string fileName = DataPath + qiShu + ".xml";

            var xml = XElement.Load(fileName);
            var data = xml.Element("Numbers");
            if (data != null)
                data.Remove();

            var e = (from item in numbers
                     select new XElement("Value", item)
                     ).ToArray();

            xml.Add(new XElement("Numbers", e));
            xml.Save(fileName);
        }

        /// <summary>
        /// 调入奖号
        /// </summary>
        /// <param name="qiShu">期数</param>
        /// <returns>奖号</returns>
        public static string[] LoadNumbers(string qiShu) {
            string fileName = DataPath + qiShu + ".xml";

            var xml = XElement.Load(fileName);
            var data = xml.Element("Numbers");
            if (data == null) {
                return new string[14];
            }
            var result = from item in data.Elements("Value")
                         select item.Value;

            return result.ToArray();
        }

        /// <summary>
        /// 获得任意N场的场次
        /// </summary>
        /// <param name="qiShu"></param>
        /// <param name="maxCount"></param>
        /// <returns></returns>
        public static string[] LoadCC(string qiShu, int maxCount) {
            string fileName = DataPath + qiShu + ".xml";

            var xml = XElement.Load(fileName);
            var data = from item in xml.Elements("MaxCount")
                       where item.Attribute("value").Value == maxCount.ToString()
                       select item.Attribute("cc").Value;
            return data.ToArray();
        }

        /// <summary>
        /// 模拟开奖
        /// </summary>
        /// <param name="n">奖号</param>
        /// <param name="f"></param>
        public static void DoSimulation(string[] numbers, FTCellData f) {
            if (numbers == null) {
                return;
            }
            if (f == null) {
                return;
            }

            for (int row = 0; row < f.RowCount; row++) {
                int rightCount = 0;
                for (int col = 0; col < 14; col++) {
                    var cellValue = f[col + 1, row];
                    if (string.IsNullOrEmpty(cellValue)) {
                        continue;
                    }

                    if (cellValue == "310") {
                        rightCount++;
                        continue;
                    }

                    var n = numbers[col];
                    if (n == "310" && cellValue != string.Empty) rightCount++;

                    if (cellValue.IndexOf(n) != -1) rightCount++;
                }

                f[16, row] = rightCount.ToString();
            }
        }


        /// <summary>
        /// 为投注表模拟开奖
        /// </summary>
        /// <param name="numbers"></param>
        /// <param name="m_touZhu"></param>
        /// <returns></returns>
        public static List<string> DoSimulationForTouZhu(string[] numbers, List<long> m_touZhu) {
            var result = new List<string>();

            var one = new List<int>();
            var two = new List<int>();
            var isNine = false;
            for (int i = 0; i < m_touZhu.Count; i++) {
                var s = FTHelper.LongToStr(m_touZhu[i]);
                int count = 0;
                for (int index = 0; index < 14; index++) {
                    var c = s[index];
                    if (c == '#') {
                        isNine = true;
                        continue;
                    }

                    if (s[index].ToString() == numbers[index])
                        count++;
                }
                if (isNine) {
                    if (count == 9) one.Add(i);
                } else {
                    if (count == 14) one.Add(i);
                    else if (count == 13) two.Add(i);
                }
            }

            result.Add(string.Format("一等奖 {0} 注", one.Count));
            foreach (var item in one) {
                result.Add(string.Format("  {1}(第{0}注)", item + 1, FTHelper.LongToStr(m_touZhu[item])));
            }
            if (!isNine) {
                result.Add(string.Format("二等奖 {0} 注", two.Count));
                foreach (var item in two) {
                    result.Add(string.Format("  {1}(第{0}注)", item + 1, FTHelper.LongToStr(m_touZhu[item])));
                }
            }
            return result;
        }

        /// <summary>
        /// 保存N场的场次组合
        /// </summary>
        /// <param name="qiShu"></param>
        /// <param name="cc"></param>
        /// <param name="maxCount"></param>
        public static void SaveCC(string qiShu, string cc, int maxCount) {
            string fileName = DataPath + qiShu + ".xml";
            var xml = XElement.Load(fileName);

            xml.Add(new XElement("MaxCount",
                        new XAttribute("value", maxCount),
                        new XAttribute("cc", cc),
                        new XElement("T1"),
                        new XElement("T2"),
                        new XElement("T3"),
                        new XElement("T4")));

            xml.Save(fileName);
        }

        public static void DeleteCC(string qiShu, string cc, int maxCount) {
            string fileName = DataPath + qiShu + ".xml";
            var xml = XElement.Load(fileName);

            var data = (from item in xml.Elements("MaxCount")
                         where (int)item.Attribute("value") == maxCount
                         && item.Attribute("cc").Value == cc
                         select item).SingleOrDefault();
            if (data != null) data.Remove();

            xml.Save(fileName);
        }

        private static void CreateInputNode(string qiShu, string cc, int maxCount, string order, string tableName) {
            string fileName = DataPath + qiShu + ".xml";

            var xml = XElement.Load(fileName);

            var maxCountValue = cc == string.Empty ? 14 : maxCount;
            var table = (from item in xml.Elements("MaxCount")
                        where (int)item.Attribute("value") == maxCountValue
                        && item.Attribute("cc").Value == cc
                        select item.Element(tableName)).SingleOrDefault();

            var data = (from item in table.Elements("Input")
                        where item.Attribute("order").Value == order
                        select item).SingleOrDefault();
            if (data != null) return;

            table.Add(new XElement("Input", new XAttribute("order", order)));
            xml.Save(fileName);
        }

        /// <summary>
        /// 复制14场数据到表1
        /// </summary>
        /// <param name="qiShu"></param>
        /// <param name="cc"></param>
        /// <param name="maxCount"></param>
        /// <param name="subIndex"></param>
        public static void CopyDataFrom14ToT1(string qiShu, string cc, int maxCount, string subIndex) {
            if (string.IsNullOrEmpty(qiShu)) {
                return;
            }
            if (string.IsNullOrEmpty(cc)) {
                return;
            }
            if (string.IsNullOrEmpty(subIndex)) {
                return;
            }

            CreateInputNode(qiShu, cc, maxCount, subIndex, "T1");

            List<DS> d;
            List<FD> f;
            CL c;
            LoadT1Data(qiShu, string.Empty, 14, subIndex, out d, out f, out c); //14场的数据

            var ccList = (from item in cc.Split('-')
                          select item).ToList();

            var dsListTemp = new List<DS>();
            for (int i = 0; i < d.Count; i++) {
                var ds = d[i];
                if (ccList.IndexOf((i + 1).ToString()) == -1) {
                    ds.One = int.MinValue;
                    ds.Zero = int.MinValue;
                    ds.Three = int.MinValue;
                } else {
                    dsListTemp.Add(new DS(ds.Three, ds.One, ds.Zero, ds.PreNumber));
                }
            }

            var result = DSHelper.ProcessAllData(dsListTemp);

            f = new List<FD>();
            foreach (var item in result) {
                f.Add(new FD(item.Key, item.Value, 0, item.Value, true));
            }

            c.From1 = -1;
            c.To1 = -1;
            c.From2 = -1;
            c.To2 = -1;

            SaveT1Data(qiShu, cc, maxCount, subIndex, d, f, c);
        }

        public static void CopyDataFrom14ToT2(string qiShu, string cc, int maxCount, string subIndex) {
            if (string.IsNullOrEmpty(qiShu)) {
                return;
            }
            if (string.IsNullOrEmpty(cc)) {
                return;
            }
            if (string.IsNullOrEmpty(subIndex)) {
                return;
            }

            CreateInputNode(qiShu, cc, maxCount, subIndex, "T2");

            List<SC> d;
            List<FD> f;
            CL c;
            LoadT2Data(qiShu, string.Empty, 14, subIndex, out d, out f, out c);

            var ccList = (from item in cc.Split('-')
                          select item).ToList();

            for (int i = 0; i < d.Count; i++) {
                var ds = d[i];
                if (ccList.IndexOf((i + 1).ToString()) == -1) {
                    ds.One = int.MinValue;
                    ds.Zero = int.MinValue;
                    ds.Three = int.MinValue;
                    ds.PreNumber = string.Empty;
                    ds.D = string.Empty;
                    ds.Z = string.Empty;
                    ds.X = string.Empty;
                }
            }

            var result = SCHelper.ProcessAllData(d);
            f = new List<FD>();
            foreach (var item in result) {
                f.Add(new FD(item.Key, item.Value, 0, item.Value, true));
            }

            c.From1 = -1;
            c.From2 = -1;
            c.To1 = c.To2 = -1;
            SaveT2Data(qiShu, cc, maxCount, subIndex, d, f, c);
        }

        public static void CopyDataFrom14ToT3(string qiShu, string cc, int maxCount, string subIndex) {
            if (string.IsNullOrEmpty(qiShu)) {
                return;
            }
            if (string.IsNullOrEmpty(cc)) {
                return;
            }
            if (string.IsNullOrEmpty(subIndex)) {
                return;
            }

            CreateInputNode(qiShu, cc, maxCount, subIndex, "T3");
            List<DZX> d;
            CellData f;
            LoadT3Data(qiShu, string.Empty, 14, subIndex, out d, out f);

            var ccList = (from item in cc.Split('-')
                          select item).ToList();

            for (int i = 0; i < d.Count; i++) {
                var ds = d[i];
                if (ccList.IndexOf((i + 1).ToString()) == -1) {
                    ds.One = int.MinValue;
                    ds.Zero = int.MinValue;
                    ds.Three = int.MinValue;
                    ds.PreNumber = string.Empty;
                    ds.D = string.Empty;
                    ds.Z = string.Empty;
                    ds.X = string.Empty;
                }
            }

            var cellData = DZXHelper.Gen(d);

            SaveT3Data(qiShu, cc, maxCount, subIndex, d, cellData);
        }

        public static void CopyDataFrom14ToT4(string qiShu, string cc, int maxCount, string subIndex) {
            if (string.IsNullOrEmpty(qiShu)) {
                return;
            }
            if (string.IsNullOrEmpty(cc)) {
                return;
            }
            if (string.IsNullOrEmpty(subIndex)) {
                return;
            }

            CreateInputNode(qiShu, cc, maxCount, subIndex, "T4");
            List<WZ> d;
            CellData f;
            string t;
            LoadT4Data(qiShu, string.Empty, 14, subIndex, out d, out f, out t);

            var ccList = (from item in cc.Split('-')
                          select item).ToList();

            for (int i = 0; i < d.Count; i++) {
                var ds = d[i];
                if (ccList.IndexOf((i + 1).ToString()) == -1) {
                    ds.Three = string.Empty;
                    ds.One = string.Empty;
                    ds.Zero = string.Empty;
                    ds.PreText = string.Empty;
                }
            }

            var cellData = WZHelper.Gen(d);

            SaveT4Data(qiShu, cc, maxCount, subIndex, d, cellData, t);
        }
    }
}
